import api from '../axios'
import { API_CONFIG } from '../config'
import { tokenManager } from './tokenManager'
import { userManager } from './userManager'

// 认证相关API
export const authApi = {
  // 登录
  login: async (username, password) => {
    try {
      const response = await api.post(API_CONFIG.authEndpoints.login, { username, password })
      if (response.status === 200) {
        // 保存token和用户信息
        const { access, refresh, user } = response.data
        tokenManager.setTokens(access, refresh)
        userManager.setUserInfo(user)
        
        return { 
          success: true, 
          data: {
            access,
            refresh,
            ...user
          }
        }
      }
      return { success: false, error: '登录失败' }
    } catch (error) {
      console.error('Login error:', error)
      return { 
        success: false, 
        error: error.response?.data?.message || '登录失败',
        details: error.response?.data
      }
    }
  },
  
  // 刷新token
  refreshToken: async () => {
    try {
      const refreshToken = tokenManager.getRefreshToken()
      if (!refreshToken) {
        throw new Error('No refresh token available')
      }

      const response = await api.post(API_CONFIG.authEndpoints.refresh, { refresh: refreshToken })
      if (response.data.status === 200) {
        const newAccessToken = response.data.access
        localStorage.setItem('accessToken', newAccessToken)
        return newAccessToken
      }
      throw new Error('Token refresh failed')
    } catch (error) {
      console.error('Token refresh failed:', error)
      tokenManager.clearTokens()
      userManager.clearUserInfo()
      window.location.href = '/login'
      throw error
    }
  },
  
  // 登出
  logout: () => {
    tokenManager.clearTokens()
    userManager.clearUserInfo()
    return Promise.resolve()
  }
} 